<template>
    <div ref="tablediv" style="padding: 10px; box-sizing: border-box;height:100%">
        <a-space style="margin-bottom:10px;">
                        <a-button type="primary" @click="addLine" size="small">新增</a-button>
                        <a-button type="primary" @click="delLine" size="small">删除</a-button>
                    </a-space>
                    <a-table stripe :bordered="true" :columns="tableColumns1"
                        :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="selectedRowKeys"
                        :loading="table.tableLoading" :data="dataForm.tableList1" :rowKey="rowKey">
                        <template #editIngredient="{ record }">
                            <div style="width:100%;height: 40px;">
                                <a-select popup-container="html"  allow-clear v-model="record.ingredient">
                                    <a-option v-for="item of pageData.data1">{{ item["partName"] }}</a-option>
                                </a-select>
                            </div>
                        </template>
                        <template #editIngredientEnglish="{ record }">
                            <div style="width:100%;height: 40px;">
                                <a-select popup-container="html"  allow-clear v-model="record.ingredientEnglish">
                                    <a-option v-for="item of pageData.data1">{{ item["englishPartName"] }}</a-option>
                                </a-select>
                            </div>
                        </template>
                        <template #editComponentcottonRatio="{ record }">
                            <div style="width:100%;height: 40px;">
                                <a-input v-model="record.componentcottonRatio" />
                            </div>
                        </template>
                        <template #editResurgence="{ record }">
                            <div style="width:100%;height: 40px;">
                                <a-input v-model="record.resurgence" />
                            </div>
                        </template>
                        <template #editComponentRemark="{ record }">
                            <div style="width:100%">
                                <a-input v-model="record.componentRemark" />
                            </div>
                        </template>
                    </a-table>
    </div>

</template>

<script lang="ts">
import { post } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, onMounted, onActivated, onUnmounted } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Form, Message, Modal } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import emitter from "@/hooks/useEventBus";
import validate from "@/hooks/useValidate";
import { DatasetComponent } from "echarts/components";
import { baseURL } from '../../../api/axios.config'
import axios from "axios";


interface Cloth {
    merceryCode: string;
}
interface ClothInfo {
    id: number | string | null;
    merceryCode: string;
    remark: string;
    merceryName: string;
    factory: string;
    deteleState: string | undefined | null;
    createName: string | undefined | null;
    createTime: string | undefined | null;
    updateName: string | undefined | null;
    updateTime: string | undefined | null;
}
export default {
    name: "EmbroideryListTable",
    setup() {
        //查询
        const scrollbar = ref(true)
        function doRefresh() {
            pageData.pageLoading = true

            post({
                url: "product/mercery/getPage",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: 0,
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {

                        table.handleSuccess(data.list);
                        pagination.setTotalSize(data.total);

                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        //检验表单是否含有中文的方法
        const hasChiese = validate.includeChinese;
        const tableColumns1 = useTableColumn([
            {
                title: "编号",
                key: "merceryCode",
                dataIndex: "merceryCode",
                width: 150
            },
            {
                title: "名称",
                key: "merceryName",
                dataIndex: "merceryName",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 150
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 150
            },
            {
                title: "操作",
                key: "id",
                dataIndex: "id",
                slotName: "action",
                width: 150, fixed: 'right'
            },
        ]);
        const scroll = {
            x: 2000,
            y: 200
        };
        const tablediv = ref(null)
        const pageData = reactive<{
            showAdd: boolean
            pageLoading: boolean,
            height: number,
            tablediv: any,
            rHeight: number | undefined,
            data1:[],
            tableList1:[]
        }>({
            showAdd: false,
            pageLoading: false,
            height: 0,
            tablediv: null,
            rHeight: 0,
            data1:[],
            tableList1:[]
        });
      
        onMounted(() => {
            
            pageData.rHeight = document.getElementById("ProductManagement")?.clientHeight
            //表格的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 200;


            }

            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementById("ProductManagement")?.clientHeight

                //表格的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 200;
                }

            })
        });

        //查询
        const selectHandler = () => {
            doRefresh();
        }
        const queryData = reactive({
            clothType: "",
        });
       
        const deleteHandler = () => {
            if (selectedRowKeys.value.length === 0) {
                return;
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    post({
                        url: "product/mercery/delete",
                        data: selectedRowKeys.value,
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            doRefresh();
                        } else {
                            Message.error({
                                content: "修改失败",
                                duration: 5000,
                            });
                        }

                    });
                },
            });
        };
      
        //导出
        const exports = () => {
            if (selectedRowKeys.value.length === 0) {
                Message.error('请先勾选')
                return
            } else {
                //将表头拼接出来
                let head = "<th>编号</th><th>名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["merceryCode"] + "</td>";
                    body += "<td>" + o["merceryName"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '布类资料', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }
        //模板下载
        const downloadHandler = () => {
            window.open(baseURL + '/product/mercery/uploadMerceryModel')
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/mercery/analyseMerceryModel', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        let tc:any[] = tableColumns1.map((o:any)=>{

let obj = {
    headerName:o.title,
    field:o.key,
    pinned:o['fixed']
}
if(o.slotName === 'action'){
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj["lockPosition"]="right"

    obj['cellRenderer'] = {
        template:`<a-tag color="#ff7d00" @click="a">修改</a-tag>`,
        setup(props:any){
            const a = () =>{
                // editHandler(props.params.data)
            }
            return {
                a
            }
        }
        
    }
}

return obj
})

let a = [{
showRowGroup: 'hide_def',
"headerName": "",
"checkboxSelection": true,
"headerCheckboxSelection": true,
"pinned": "left",
"width": 50,
resizable: false,
filter:false,
sortable:false,
minWidth: 50,
maxWidth: 50,
lockPosition:"left",
}]
tc = a.concat(tc)
        const defaultColDef = {
            sortable: true,
            resizable:true,
            filter: true,
            // flex: 1
          }
        return {
            defaultColDef,
            tc,
            scroll,
            scrollbar,
            tablediv,
            downloadHandler,
            importHandler,
            hasChiese,
            deleteHandler,
            selectedRowKeys,
            pagination,
            tableColumns1,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
           
        };
    },
     components: { Toolbar,  },
};
</script>
<style scoped lang="less">
    form{
        width: 100% !important;
    }
</style>
